# -*- coding: utf-8 -*-
# @Time    : 2024/03/20 15:21
# @Author  : Jonny
# @File    : LuckLogHelperUtils.py
# @Describe: 日志记录逻辑服务层

import time
import logging
import base64
import requests
import json
import subprocess
import socket
import platform


class LuckLogHelperUtils(object):
    def __init__(self, config):
        self.config = config

    def run_command(self, cmd):
        result = subprocess.run(cmd, shell=True, capture_output=True)
        return result.stdout.decode('utf-8')

    def __read_linux_ip(self, container_name):
        try:
            cmd = "docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' " + container_name
            output = self.run_command(cmd).strip()
            if len(output) > 0:
                ip_addresses = [x for x in output.split('\n') if x]
                return ip_addresses[0].strip()
            else:
                return None
        except Exception as e:
            logging.exception('根据容器名称读取宿主机IP异常：%s', e)
            return None

    CONTENT_TYPE = 'application/json'
    # 添加正常记录
    def add_visit_log(self, parameters):
        auth = str(base64.b64encode(f'{self.config["log_url_basic_auth1"]}:{self.config["log_url_basic_auth2"]}'.encode('utf-8')),'utf-8')
        headers = {
            'Content-Type': self.CONTENT_TYPE,
            'Authorization': f'Basic {auth}'
        }
        url = f'{self.config["log_url"]}/sys/log/visit/add'

        parameters["reqtime"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        parameters["log_app_key"] = self.config["log_app_key"]
        parameters["log_app_secret"] = self.config["log_app_secret"]

        # 获取主机名
        host = socket.gethostname()
        # 获取IP地址
        ip = self.__read_linux_ip(host)
        if ip is None:
            ip = socket.gethostbyname(host)
        # 获取操作系统
        system = platform.system() + ' ' + platform.release()
        parameters["reqip"] = ip
        parameters["reqhost"] = host
        parameters["reqsystem"] = system

        res = requests.post(url, data=json.dumps(parameters), headers=headers)
        return res.text

    # 添加异常记录
    def add_error_log(self, parameters):
        auth = str(base64.b64encode(
            f'{self.config["log_url_basic_auth1"]}:{self.config["log_url_basic_auth2"]}'.encode('utf-8')),
                   'utf-8')
        headers = {
            'Content-Type': self.CONTENT_TYPE,
            'Authorization': f'Basic {auth}'
        }
        url = f'{self.config["log_url"]}/sys/log/error/add'

        parameters["reqtime"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        parameters["log_app_key"] = self.config["log_app_key"]
        parameters["log_app_secret"] = self.config["log_app_secret"]

        # 获取主机名
        host = socket.gethostname()
        # 获取IP地址
        ip = self.__read_linux_ip(host)
        if ip is None:
            ip = socket.gethostbyname(host)
        # 获取操作系统
        system = platform.system() + ' ' + platform.release()
        parameters["reqip"] = ip
        parameters["reqhost"] = host
        parameters["reqsystem"] = system

        res = requests.post(url, data=json.dumps(parameters), headers=headers)
        return res.text
